using EnvDTE;
using Microsoft.Practices.RecipeFramework;
using VSSDKAssist.Assets.Actions.Base;
using VSSDKAssist.Assets.Helpers;

namespace VSSDKAssist.Assets.Actions.VisualStudio
{
	/// <summary>
	/// Action that adds a folder to a Project
	/// </summary>
	public class AddProjectFolderAction : ActionBase
	{
		#region Fields
		private string folderName;

		/// <summary>
		/// Gets or sets the name of the folder.
		/// </summary>
		/// <value>The name of the folder.</value>
		[Input(Required = true)]
		public string FolderName
		{
			get { return folderName; }
			set { folderName = value; }
		}

		Project project;
		/// <summary>
		/// Gets or sets the project.
		/// </summary>
		/// <value>The project.</value>
		[Input(Required = false)]
		public Project Project
		{
			get { return project; }
			set { project = value; }
		}

		private ProjectItem folderAdded;

		/// <summary>
		/// Gets or sets the folder added.
		/// </summary>
		/// <value>The folder added.</value>
		[Output]
		public ProjectItem FolderAdded
		{
			get { return folderAdded; }
			set { folderAdded = value; }
		}
		#endregion

		#region Protected Implementation
		/// <summary>
		/// Called when [execute].
		/// </summary>
		protected override void OnExecute()
		{
			string[] foldersArray = this.folderName.Split('\\');

			if(project == null)
			{
				project = VisualStudio.SelectedItems.Item(1).Project;
			}

			if(project != null)
			{
				if(foldersArray.Length > 0)
				{
					ProjectItem lastItem = VSIPHelper.FindItemByName(project.ProjectItems, foldersArray[0], false);

					if(lastItem == null)
					{
						lastItem = AddFolder(project.ProjectItems, foldersArray[0]);

						for(int i = 1; i < foldersArray.Length; i++)
						{
							lastItem = AddFolder(lastItem.ProjectItems, foldersArray[i]);
						}
					}
					else
					{
						for(int i = 1; i < foldersArray.Length; i++)
						{
							ProjectItem itemTemp = VSIPHelper.FindItemByName(lastItem.ProjectItems, foldersArray[i], false);

							if(itemTemp == null)
							{
								lastItem = AddFolder(lastItem.ProjectItems, foldersArray[i]);
							}
							else
							{
								lastItem = itemTemp;
							}
						}
					}

					folderAdded = lastItem;
				}
			}
		} 
		#endregion

		#region Private Implementation
		private static ProjectItem AddFolder(ProjectItems items, string folder)
		{
			return items.AddFolder(folder, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);
		} 
		#endregion
	}
}